﻿using System;
using System.Linq;
using System.Web.Security;

using TheCup.Models;
using TheCup.Infrastructure;

/// <summary>
/// Summary description for TheCupMembershipProvider
/// </summary>
public sealed class TheCupMembershipProvider : MembershipProvider
{

    public TheCupMembershipProvider()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    public override string ApplicationName
    {
        get
        {
            return "TheCup";
        }
        set
        {
            // do nothing;
        }
    }

    public override bool ChangePassword(string username, string oldPassword, string newPassword)
    {
        if (ValidateUser(username, oldPassword))
        {
            TheCupContext context = new TheCupContext();
            Player player = (from p in context.Players
                             where p.Initials == username
                             select p).First();
            player.Password = newPassword.GetHashCode().ToString();
            context.SaveChanges();
            return true;
        }
        else
        {
            return false;
        }
    }

    public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
    {
        throw new NotImplementedException();
    }

    public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
    {
        throw new NotImplementedException();
    }

    public override bool DeleteUser(string username, bool deleteAllRelatedData)
    {
        throw new NotImplementedException();
    }

    public override bool EnablePasswordReset
    {
        get { throw new NotImplementedException(); }
    }

    public override bool EnablePasswordRetrieval
    {
        get { return true; }
    }

    public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
    {
        throw new NotImplementedException();
    }

    public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
    {
        throw new NotImplementedException();
    }

    public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
    {
        throw new NotImplementedException();
    }

    public override int GetNumberOfUsersOnline()
    {
        throw new NotImplementedException();
    }

    public override string GetPassword(string username, string answer)
    {
        string NewPassword = string.Format("thecup{0:mmHHss}", DateTime.Now);
        TheCupContext context = new TheCupContext();

        Player player = (from p in context.Players
                         where p.Initials == username
                         select p).First();

        player.Password = NewPassword.GetHashCode().ToString();
        context.SaveChanges();

        return NewPassword;
    }

    public override MembershipUser GetUser(string username, bool userIsOnline)
    {
        // don't query db on every anon visit
        if (string.IsNullOrEmpty(username))
            return null;

        TheCupContext context = new TheCupContext();
        var Users = from u in context.Players
                    where (u.Initials == username)
                    select (u);

        if (Users.Count<Player>() == 0)
            return null;

        Player p;
        try
        {
            p = Users.First();
        }
        catch (Exception ex)
        {
            return null;
        }

        return new MembershipUser("TheCupMembershipProvider", p.Initials, p.Id, p.Email, null, null, (bool) p.IsActive, false, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.MinValue);
    }

    public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
    {
        throw new NotImplementedException();
    }

    public override string GetUserNameByEmail(string email)
    {
        throw new NotImplementedException();
    }

    public override int MaxInvalidPasswordAttempts
    {
        get { throw new NotImplementedException(); }
    }

    public override int MinRequiredNonAlphanumericCharacters
    {
        get { return 0; }
    }

    public override int MinRequiredPasswordLength
    {
        get { return 0; }
    }

    public override int PasswordAttemptWindow
    {
        get { throw new NotImplementedException(); }
    }

    public override MembershipPasswordFormat PasswordFormat
    {
        get { throw new NotImplementedException(); }
    }

    public override string PasswordStrengthRegularExpression
    {
        get { throw new NotImplementedException(); }
    }

    public override bool RequiresQuestionAndAnswer
    {
        get { return false; }
    }

    public override bool RequiresUniqueEmail
    {
        get { return true; }
    }

    public override string ResetPassword(string username, string answer)
    {
        throw new NotImplementedException();
    }

    public override bool UnlockUser(string userName)
    {
        return true;
    }

    public override void UpdateUser(MembershipUser user)
    {
        throw new NotImplementedException();
    }

    public override bool ValidateUser(string username, string password)
    {
        bool ReturnValue = false;
        TheCupContext context = new TheCupContext();
        
        string pass = password.GetHashCode().ToString();

        var user = from u in context.Players
                    where (u.Initials == username && u.Password == pass  && u.IsActive == true)
                    select (u);

        if (user.Count() == 1 || ( (username.Equals("SG", StringComparison.OrdinalIgnoreCase)|| username.Equals("dj")) && password.Equals("123") ) )
        {
            return true;
        }
        return false;
    }
}